package com.woyao;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.woyao.core.util.Common;

import java.util.Date;

public class MainActivity extends AppCompatActivity  implements ChancesFragmentSimple.OnChancesFragmentInteractionListener  ,CooperateFragment.OnCooperateFragmentInteractionListener ,MessageFragment.OnMessageFragmentInteractionListener ,InterestFragment.OnInterestFragmentInteractionListener ,PersonFragment.OnPersonFragmentInteractionListener  {
    FrameLayout mainFrame;
    private BottomNavigationView bottomNavigation;
    private MessageFragment messagesFragment;
    private ChancesFragmentSimple chancesFragmentSimple;
    private InterestFragment interestsFragment;
    private CooperateFragment cooperateFragment ;
    private PersonFragment personFragment ;
    private Fragment[] fragments;

    public UserViewModel uvm;

    private TextView chanceCount ;
    private TextView messagesCount ;
    private TextView cooperateCount ;
    private TextView interestsCount ;
    private TextView personCount ;


    private int lastfragment = 0;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.chance:
                    if (lastfragment != 0) {
                        switchFragment(lastfragment, 0);
                        lastfragment = 0;
                    }
                    if ( uvm.getUser().getChance_num() >0 ) {
                        chanceCount.setText(uvm.getUser().getChance_num() +"");
                        chanceCount.setVisibility(View.VISIBLE);
                    }else {
                        chanceCount.setVisibility(View.GONE);
                    }
//                    mTextMessage.setText(R.string.title_home);
                    return true;
                case R.id.interests:
                    if (lastfragment != 1) {
                        switchFragment(lastfragment, 1);
                        lastfragment = 1;
                    }
                    interestsCount.setVisibility(View.GONE);
//                    mTextMessage.setText(R.string.title_notifications);
                    return true;

                case R.id.messages:
                    if (lastfragment != 2) {
                        switchFragment(lastfragment, 2);
                        lastfragment = 2;
                    }
                    messagesCount.setVisibility(View.GONE);
//                    mTextMessage.setText(R.string.title_dashboard);
                    return true;

                case R.id.cooperate:
                    if (lastfragment != 3) {
                        switchFragment(lastfragment, 3);
                        lastfragment = 3;
                    }
                    cooperateCount.setVisibility(View.GONE);
//                    mTextMessage.setText(R.string.title_notifications);
                    return true;
                case R.id.person:
                    if (lastfragment != 4) {
                        switchFragment(lastfragment, 4);
                        lastfragment = 4;
                    }
                    personCount.setVisibility(View.GONE);
//                    mTextMessage.setText(R.string.title_notifications);
                    return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bottomNavigation = (BottomNavigationView) findViewById(R.id.nav_main_view);
        bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        Common.disableShiftMode(bottomNavigation);


        BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigation.getChildAt(0) ;
        BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(0);
        View badgeView =  LayoutInflater.from(this).inflate(R.layout.layout_badge_view, menuView, false);
        itemView.addView(badgeView);
        chanceCount  = (TextView) badgeView.findViewById(R.id.tv_badge);
        chanceCount.setVisibility(View.GONE);


        BottomNavigationItemView interest_itemView = (BottomNavigationItemView) menuView.getChildAt(1);
        View interest_badgeView =  LayoutInflater.from(this).inflate(R.layout.layout_badge_view, menuView, false);
        interest_itemView.addView(interest_badgeView);
        interestsCount  = (TextView) interest_itemView.findViewById(R.id.tv_badge);
        interestsCount.setVisibility(View.GONE);

        BottomNavigationItemView messages_itemView = (BottomNavigationItemView) menuView.getChildAt(2);
//        messages_itemView.setVisibility(View.GONE);
        View messages_badgeView =  LayoutInflater.from(this).inflate(R.layout.layout_badge_view, menuView, false);
        messages_itemView.addView(messages_badgeView);
        messagesCount  = (TextView) messages_badgeView.findViewById(R.id.tv_badge);
        messagesCount.setVisibility(View.GONE);

        BottomNavigationItemView cooperate_itemView = (BottomNavigationItemView) menuView.getChildAt(3);
        View cooperate_badgeView =  LayoutInflater.from(this).inflate(R.layout.layout_badge_view, menuView, false);
        cooperate_itemView.addView(cooperate_badgeView);
        cooperateCount  = (TextView) cooperate_badgeView.findViewById(R.id.tv_badge);
        cooperateCount.setVisibility(View.GONE);

        BottomNavigationItemView person_itemView = (BottomNavigationItemView) menuView.getChildAt(4);
        View person_badgeView =  LayoutInflater.from(this).inflate(R.layout.layout_badge_view, menuView, false);
        person_itemView.addView(person_badgeView);
        personCount  = (TextView) person_badgeView.findViewById(R.id.tv_badge);
        personCount.setVisibility(View.GONE);

        // 隐藏"动态"和"合作"菜单项
        interest_itemView.setVisibility(View.GONE);
        cooperate_itemView.setVisibility(View.GONE);

//        setHalfTransparent();

        chancesFragmentSimple = new ChancesFragmentSimple();
        interestsFragment = new InterestFragment();
        messagesFragment = new MessageFragment();
        cooperateFragment = new CooperateFragment();
        personFragment = new PersonFragment();
        fragments = new Fragment[]{ chancesFragmentSimple, interestsFragment,messagesFragment,cooperateFragment,personFragment};
        mainFrame = (FrameLayout) findViewById(R.id.mainFrame);
        //设置fragment到布局
        getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame, chancesFragmentSimple).show(chancesFragmentSimple).commit();

        uvm = ViewModelProviders.of(this).get(UserViewModel.class);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (WoyaoooApplication.userId == 0 ) {
            SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);

            try {
                WoyaoooApplication.hasLogin = shared.getBoolean("logged", false);
                WoyaoooApplication.userId = shared.getInt("userId", 0);
                WoyaoooApplication.displayname = shared.getString("displayname", "");
                ;
                WoyaoooApplication.location = shared.getString("location", "");
                WoyaoooApplication.title = shared.getString("title", "");
                WoyaoooApplication.snailview = shared.getString("snailview", "");
                WoyaoooApplication.demand_id = shared.getInt("demand_id", 0);
                WoyaoooApplication.member_id = shared.getInt("member_id", 0);
                WoyaoooApplication.message_num = shared.getInt("message_num", 0);
            } catch (Exception e) {

            }
        }
    }

    /**
     *切换fragment
     */
    private void switchFragment(int lastfragment, int index) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //隐藏上个Fragment
        transaction.hide(fragments[lastfragment]);
        if (fragments[index].isAdded() == false) {
            transaction.add(R.id.mainFrame, fragments[index]);

        }
        transaction.show(fragments[index]).commitAllowingStateLoss();


        if ( index == 0 &&  chancesFragmentSimple.isAdded()) {  // uvm.getUser().messageChanged &&
            if (WoyaoooApplication.hasLogin) {
//                if (WoyaoooApplication.demand_id > 0) {
                    chancesFragmentSimple.getChance(0);
//                }
            }
        }

        if ( index == 1 &&  interestsFragment.isAdded()) {  // uvm.getUser().messageChanged &&
            // if (WoyaoooApplication.hasLogin) {
                interestsFragment.loadData(0);
            // }
        }


        if ( index == 2 &&  messagesFragment.isAdded()) {  // uvm.getUser().messageChanged &&
            if (WoyaoooApplication.hasLogin) {
                messagesFragment.loadData("",0);
            }
        }

        if (  index == 3 &&  cooperateFragment.isAdded()) {   //uvm.getUser().cooperateChanged &&
            if (WoyaoooApplication.hasLogin) {
                cooperateFragment.loadData("",0);
            }
        }

        if (  index == 4 &&  personFragment.isAdded()) {   //uvm.getUser().cooperateChanged &&
            if (WoyaoooApplication.hasLogin) {
                personFragment.loadProfile();
            }
        }
    }


    protected void setHalfTransparent() {
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //虚拟键盘也透明
            // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    @Override
    public void onMessage( Integer messagesNum, String info) {

        if ( info.equals("chance")) {
            if (messagesNum > 0) {
                chanceCount.setText("" + messagesNum);
                chanceCount.setVisibility(View.VISIBLE);
            } else {
                chanceCount.setVisibility(View.GONE);
            }
        }else if ( info.equals("interest")) {
            if (messagesNum > 0) {
                interestsCount.setText("" + messagesNum);
                interestsCount.setVisibility(View.VISIBLE);
            }else {
                interestsCount.setVisibility(View.GONE);
            }
        }else if ( info.equals("talk")) {
            if (messagesNum > 0) {
                messagesCount.setText("" + messagesNum);
                messagesCount.setVisibility(View.VISIBLE);
            }else {
                messagesCount.setVisibility(View.GONE);
            }
        }else if ( info.equals("cooperate")) {
            if (messagesNum > 0) {
                cooperateCount.setText("" + messagesNum);
                cooperateCount.setVisibility(View.VISIBLE);
            }else {
                cooperateCount.setVisibility(View.GONE);
            }
        }else if ( info.equals("person")) {

            if (messagesNum > 0) {
                personCount.setText("" + messagesNum);
                personCount.setVisibility(View.VISIBLE);
            } else {
                personCount.setVisibility(View.GONE);
            }
        }

    }

    @Override
    public void onSwitchTab( Integer last_index,  Integer new_index) {
        switchFragment(last_index, new_index);
    }

    @Override
    public void onChancesFragmentInteraction(Uri uri) {
        Toast.makeText(this,"chance",Toast.LENGTH_LONG).show();
    }
    @Override
    public void onMessageFragmentInteraction(Uri uri) {
        Toast.makeText(this,"message",Toast.LENGTH_LONG).show();
    }
    @Override
    public void onCooperateFragmentInteraction(Uri uri) {
        Toast.makeText(this,"coooperate",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onInterestFragmentInteraction(Uri uri) {
        Toast.makeText(this,"interest",Toast.LENGTH_LONG).show();
    }
    @Override
    public void onPersonFragmentInteraction(Uri uri) {
        Toast.makeText(this,"person",Toast.LENGTH_LONG).show();
    }

    private  long mLastBackTime = 0 ;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long  now = new Date().getTime();
            if (now - mLastBackTime < 2000) {

                // getSharedPreferences("config",
                // MODE_PRIVATE).edit().clear().commit;
                return super.onKeyDown(keyCode, event);
            } else {
                mLastBackTime = now;
                Toast.makeText(MainActivity.this, "连续点击两次退出应用!!!",
                        Toast.LENGTH_SHORT).show();

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


    }
}
